package HOT;

/**
 * Author  zxy
 * Date  2023/7/14 18:29
 */
public class TwoThreadPrint {

    public static void main(String[] args) {

        PrintObject printObject = new PrintObject(true, 50);

        new Thread(() -> {
            printObject.printChar(true, 'A');
        }).start();

        new Thread(() -> {
            printObject.printChar(false, 'B');
        }).start();
    }
}

class PrintObject {
    private boolean flag;
    private int loopNum;

    public PrintObject (boolean flag, int loopNum) {
        this.flag = flag;
        this.loopNum = loopNum;
    }

    public void printChar (boolean curFlag, char c) {
        for (int i = 0; i < loopNum; i++) {
            synchronized (this) {
                if (curFlag != flag) {
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                System.out.println(i + " _ " + c);
                flag = !flag;
                this.notify();
            }
        }
    }
}
